/*******************************************************************************
 * Copyright (c) 2010-2011 Robert Fraser                                       *
 *                                                                             *
 * Permission is hereby granted, free of charge, to any person obtaining a     *
 * copy of this software and associated documentation files (the "Software"),  *
 * to deal in the Software without restriction, including without limitation   *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,    *
 * and/or sell copies of the Software, and to permit persons to whom the       *
 * Software is furnished to do so, subject to the following conditions:        *
 *                                                                             *
 *   - The above copyright notice and this permission notice shall be included *
 *     in all copies or substantial portions of the Software.                  *
 *                                                                             *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,    *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING     *
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER         *
 * DEALINGS IN THE SOFTWARE.                                                   *
 *******************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using zeal.util;

namespace zeal.core
{
    public sealed class TextureGraph
    {
        private static readonly Dictionary<Type, Func<TextureGraph, TextureNode>> _textureNodeFactories = new Dictionary<Type, Func<TextureGraph, TextureNode>>();
        private readonly Dictionary<TextureInputPort, LinkedList<TextureOutputPort>> _inputsToOutputs = new Dictionary<TextureInputPort, LinkedList<TextureOutputPort>>();
        private readonly Dictionary<TextureOutputPort, LinkedList<TextureInputPort>> _outputsToInputs = new Dictionary<TextureOutputPort, LinkedList<TextureInputPort>>();
        private readonly HashSet<TextureNode> _nodes = new HashSet<TextureNode>();

        public TNode add<TNode>() where TNode : TextureNode { return (TNode) add(typeof(TNode)); }
        public TextureNode add(TextureNodeInfo info) { return add(info.type); }
        public TextureNode add(Type nodeType)
        {
            TextureNode node = _textureNodeFactories.getOrAdd(nodeType, type => (Func<TextureGraph, TextureNode>)
                Delegate.CreateDelegate(typeof(Func<TextureGraph, TextureNode>), null, 
                type.GetMethod("getInstance", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)))(this);
            add(node);
            return node;
        }

        public void add(TextureNode node)
        {
            if (node.graph != this) throw new InvalidNodeException("The texture node of type {0} is not a member of this graph", node.GetType().Name);
            if (_nodes.Contains(node)) throw new DuplicateNodeException("The texture node of type {0} is already in the graph", node.GetType().Name);
            foreach (TextureInputPort port in node.inputPorts)
                _inputsToOutputs.Add(port, new LinkedList<TextureOutputPort>());
            foreach (TextureOutputPort port in node.outputPorts)
                _outputsToInputs.Add(port, new LinkedList<TextureInputPort>());
            _nodes.Add(node);
        }

        public bool remove(TextureNode node)
        {
            checkExists(node);
            _nodes.Remove(node);
            foreach (TextureInputPort port in node.inputPorts)
            {
                foreach (TextureOutputPort port2 in _inputsToOutputs[port])
                    _outputsToInputs[port2].Remove(port);
                _inputsToOutputs.Remove(port);
            }
            foreach (TextureOutputPort port in node.outputPorts)
            {
                foreach (TextureInputPort port2 in _outputsToInputs[port])
                    _inputsToOutputs[port2].Remove(port);
                _outputsToInputs.Remove(port);
            }
            return true;
        }

        public bool connect(TextureInputPort input, TextureOutputPort output)
        {
            // If they're already connected, do nothing. Note that this method will ensure that both nodes exist
            // in this graph
            if (areConnected(input, output) || input.node == output.node)
                return false;

            // If adding this connection would break the invariant that we're acyclic, throw an exception
            if(wouldIntroduceCycle(input, output))
                throw new CyclicGraphException("Cannot connect {0} and {1}: Doing so would introduce a cycle", input, output);

            // Ensure that the types match
            TextureType tIn = input.type;
            TextureType tOut = output.type;
            if (!TextureType.canConvert(tIn, tOut))
                throw new TextureTypeCastException("TextureNode {0} of type {1} cannot be connected to node {2} of type {3}", output, tOut, input, tIn);

            // Actually connect the nodes
            _inputsToOutputs[input].AddLast(output);
            _outputsToInputs[output].AddLast(input);
            if(tIn.isVariable ^ tOut.isVariable)
            {
                if (tIn.isVariable) input.node.unifyTypeGroup();
                if (tOut.isVariable) output.node.unifyTypeGroup();
            }
            return true;
        }

        public bool disconnect(TextureInputPort input, TextureOutputPort output)
        {
            if (!areConnected(input, output) || input.node == output.node)
                return false;
            _inputsToOutputs[input].Remove(output);
            _outputsToInputs[output].Remove(input);
            if(input.info.type.isVariable) input.node.unifyTypeGroup();
            if(output.info.type.isVariable) output.node.unifyTypeGroup();
            return true;
        }

        public bool areConnected(TextureInputPort input, TextureOutputPort output)
        {
            checkExists(input.node);
            checkExists(output.node);
            return _inputsToOutputs[input].Contains(output);
        }

        public bool hasConnections(TextureNode node)
        {
            checkExists(node);
            foreach(TextureInputPort port in node.inputPorts)
                if(_inputsToOutputs[port].Count > 0)
                    return true;
            foreach (TextureOutputPort port in node.outputPorts)
                if (_outputsToInputs[port].Count > 0)
                    return true;
            return false;
        }

        public bool wouldIntroduceCycle(TextureInputPort input, TextureOutputPort output)
        {
            checkExists(input.node);
            checkExists(output.node);
            return wouldIntroduceCycleInternal(input.node, output.node);
        }

        public void write(Stream stream)
        {
            new XElement("TextureGraph",
                new XElement("Nodes", nodes.Select(node => 
                    new XElement(node.info.name, 
                        new XAttribute("id", node.id),
                        new XAttribute("x", node.x),
                        new XAttribute("y", node.y))).ToArray()),
                new XElement("Edges", edges.Select(edge => 
                    new XElement("Edge",
                        new XAttribute("inputNode", edge.input.node.id),
                        new XAttribute("inputPort", edge.input.portInfo.name),
                        new XAttribute("outputNode", edge.output.node.id),
                        new XAttribute("outputPort", edge.output.portInfo.name))).ToArray())).Save(stream);
        }

        public IEnumerable<TextureNode> nodes { get { return _nodes; } }
        public IEnumerable<Edge> edges { get { return _inputsToOutputs.SelectMany(kvp => kvp.Value, (kvp, output) => new Edge(kvp.Key, output)); } }
        
        private bool wouldIntroduceCycleInternal(TextureNode node, TextureNode source)
        {
            if(node == source)
                return true;
            foreach(TextureOutputPort outputPort in node.outputPorts)
                foreach(TextureInputPort next in _outputsToInputs[outputPort])
                    if(wouldIntroduceCycleInternal(next.node, source))
                        return true;
            return false;
        }

        public IEnumerable<TextureInputPort>  outputsOf(TextureOutputPort port) { checkExists(port.node); return _outputsToInputs[port]; }
        public IEnumerable<TextureOutputPort> inputsOf(TextureInputPort port)   { checkExists(port.node); return _inputsToOutputs[port]; }
        public IEnumerable<TextureInputPort>  outputsOf(TextureNode node)       { checkExists(node); return node.outputPorts.SelectMany(outputsOf); }
        public IEnumerable<TextureOutputPort> inputsOf(TextureNode node)        { checkExists(node); return node.inputPorts.SelectMany(inputsOf); }

        // Separating this out into three methods so checkExists() can be inlined
        private static void throwInvalidNodeException() { throw new InvalidNodeException("Node is not a member of this graph"); }
        private static void throwMissingNodeException() { throw new MissingNodeException("Node has been removed from the graph"); }
        private void checkExists(TextureNode node)
        {
            if (node.graph != this)    throwInvalidNodeException();
            if(!_nodes.Contains(node)) throwMissingNodeException();
        }

        public sealed class Edge
        {
            public readonly TextureInputPort input;
            public readonly TextureOutputPort output;

            internal Edge(TextureInputPort input, TextureOutputPort output)
            {
                this.input = input;
                this.output = output;
            }
        }
    }
}